package cn.wolfcode.shiro;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.mapper.RoleMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CrmRealm extends AuthorizingRealm {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //通过token获取用户名（用户登录的时候填的）
        Object username = token.getPrincipal();
        //判断是否存在数据库
        Employee employee = employeeMapper.selectByName((String) username);
        if(employee!=null){
            //身份信息，凭证信息（正确），盐，当前realm的名字
            return new SimpleAuthenticationInfo(employee,employee.getPassword(),
                    ByteSource.Util.bytes(username),"CrmRealm");
        }
        //返回值就是查询出来的数据，如果查到这个账号，就应该返回该账号的正确的数据，如果查不到这个账号，就返回null
        return null;
    }

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("===========================================");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前登录用户 UserContext.getUser()
        Subject subject = SecurityUtils.getSubject();
        //获取主体的身份信息
        Employee employee = (Employee)subject.getPrincipal();
        //判断是否是超级管理员
        if(employee.isAdmin()){
            info.addRole("ADMIN"); //方便后续判断是否管理员可以直接用subject来判断
            info.addStringPermission("*:*"); //权限通配符
        }else{
            //根据用户的id查询该用户拥有的角色编码
            List<Role> roles = roleMapper.selectByEmpId(employee.getId());
            ArrayList<String> roleSnList = new ArrayList<>();
            for (Role role : roles) {
                roleSnList.add(role.getSn()); //放入角色的编码
            }
            info.addRoles(roleSnList);
            //根据用户的id查询该用户拥有的权限表达式
            List<String> permissions = permissionMapper.selectByEmpId(employee.getId());
            info.addStringPermissions(permissions);
        }
        return info;
    }


}
